package HTTP

import (
	"SQL/FSDB"
	"encoding/json"
	"net/http"
)

func alterObjectData(w http.ResponseWriter, req *http.Request) {

	var resCode = Success
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	objectID := req.FormValue("objectID")
	nickname := req.FormValue("nickname")
	icon := req.FormValue("icon")
	customInfo := req.FormValue("customInfo")

	ok := false
	if ok, resCode, msg = isArgsEmpty(objectID, nickname, icon, customInfo); ok {
		return
	}
	if ok, resCode, msg = isValidID(objectID, "ObjectID"); !ok {
		return
	}
	if ok, resCode, msg = isValidNickname(nickname); !ok {
		return
	}
	if ok, resCode, msg = isValidIcon(icon); !ok {
		return
	}
	if ok, resCode, msg = isValidCustomInfo(customInfo); !ok {
		return
	}

	customJSON, err := json.Marshal(customInfo)
	if err != nil {
		msg = "customInfo解析失败！\n错误详情：" + err.Error()
		resCode = errMarshalJSONFailed
		return
	}
	errCode, errMsg := writeObjInfoToDB(objectID, nickname, icon, customJSON)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
}

func writeObjInfoToDB(objectID string, nickname string, icon string, customInfo []byte) (errCode int, errMsg string) {

	objInfoSQL := `UPDATE objects 
					SET nickname=$1,icon=$2,custom=$3 
					WHERE id = $4;`
	_, err := FSDB.Exec(objInfoSQL, nickname, icon, customInfo, objectID)

	if err != nil {
		return errDBExecFailed, err.Error()
	}
	return Success, "修改资料成功！"
}
